/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.ee.persistence;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ejb.EJB;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.ee.aop.LoggerBean;

/**
 *
 * @author Gabriel Bran <gbran.u@gmail.com>
 */
public abstract class AbstractTemplate {

    @EJB
    private LoggerBean logger;
    @PersistenceContext
    private EntityManager entityManager;

    protected <T extends Query> T setQueryParameters(T query, List<Object> parameters) {
        return setParameterList(query, parameters);
    }

    protected <T extends Query> T setQueryParameters(T query, List<Object> parameters, int firstResult, int maxResult) {
        return setParameterList(query, parameters, firstResult, maxResult);
    }

    protected <T extends Query> T setQueryParameters(T query, HashMap<?, Object> parameters) {
        return setParameterMap(query, parameters);
    }

    protected <T extends Query> T setQueryParameters(T query, HashMap<?, Object> parameters, int firstResult, int maxResult) {
        return setParameterMap(query, parameters, firstResult, maxResult);
    }

    private <T extends Query> T setParameterList(T query, List<Object> parameters) {
        for (int i = 1; i <= parameters.size(); i++) {
            query.setParameter(i, parameters.get(i));
        }
        return query;
    }

    private <T extends Query> T setParameterList(T query, List<Object> parameters, int firstResult, int maxResult) {
        return setQueryLimitResult(setParameterList(query, parameters), firstResult, maxResult);
    }

    private <T extends Query> T setParameterMap(T query, HashMap<?, Object> parameters) {
        for (Map.Entry<?, Object> parameter : parameters.entrySet()) {
            if (parameter.getKey() instanceof Integer) {
                query.setParameter((Integer) parameter.getKey(), parameter.getValue());
            } else {
                query.setParameter((String) parameter.getKey(), parameter.getValue());
            }
        }
        return query;
    }

    private <T extends Query> T setParameterMap(T query, HashMap<?, Object> parameters, int firstResult, int maxResult) {
        return setQueryLimitResult(setParameterMap(query, parameters), firstResult, maxResult);
    }

    private <T extends Query> T setQueryLimitResult(T query, int firstResult, int maxResult) {
        query.setFirstResult(firstResult);
        query.setMaxResults(maxResult);
        return query;
    }

    protected EntityManager getEntityManager() {
        return entityManager;
    }

    public LoggerBean getLogger() {
        return logger;
    }
}
